package com.augurit.smartform.web.parser;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.base.extmodel.inner.AppTreeNode;
import com.augurit.common.base.extmodel.inner.MultiEntityTreeNode;
import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.util.ExtUtils;
import com.augurit.smartform.constant.PageConstant;
import com.augurit.smartform.converter.PageConverter;
import com.augurit.smartform.converter.PageDirConverter;
import com.augurit.smartform.database.dialect.Dialect;
import com.augurit.smartform.entity.SmPage;
import com.augurit.smartform.entity.SmPageDir;
import com.augurit.smartform.mgmt.SmartPageTreeNode;
import com.augurit.smartform.service.IPageMgmtService;
import com.augurit.smartform.service.ISmartPageDirService;
import com.augurit.smartform.web.parser.form.SmPageDirForm;
import com.augurit.smartform.web.parser.form.SmPageForm;

@Results({
	@Result(name = ExtCrudActionSupport.RELOAD, location = "page-mgmt.action", type = "redirect"),
	@Result(name = ExtCrudActionSupport.SUCCESS, location = "/smartform/page-mgmt/smart-page-mgmt.jsp")
})
public class PageMgmtAction extends ExtCrudActionSupport<SmPageForm> {
	@Autowired
	private IPageMgmtService pageMgmtService;
	@Autowired
	private ISmartPageDirService pageDirService;
	
	private String nodeId;	//页面管理树结点ID，由 Entity类名 + "#" + Entity对象ID 组成 
	private SmPageForm form;
	private Long id;
	private Long[] ids;
	private Page<SmPageForm> page=new Page<SmPageForm>(10);
	
	private static final Logger log = LoggerFactory.getLogger(PageMgmtAction.class);
	
	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 查询智能表单页面的列表
	 */
	public String list() throws Exception {
		String formPathPrefix=getRootPath() + getRequest().getContextPath()+PageConstant.PREFIX_PAGE_PATH;
		ExtUtils.initPageFromExtGridParam(getRequest(), page);
		pageMgmtService.findPageWithTableInfo(page, form);
		this.setFormPath(formPathPrefix);
		ExtBaseAction.extRenderGridJson(page);
		return null;
	}
	
	/**
	 * 页面管理的树列表
	 */
	public void getPageTree(){
		MultiEntityTreeNode node = SmartPageTreeNode.build(nodeId);
		List<SmartPageTreeNode> result = getChildren(node);
		this.extRenderListJson(result, false);
	}
	
	/**
	 * 检查是否修改数据页面
	 */
	public void checkDbRelation(){
		List<SmPageForm> list=new ArrayList<SmPageForm>();
		for(Long id : ids){
			SmPageForm smPage=pageMgmtService.getDbRelationPage(id);
			if(smPage!=null){
				list.add(smPage);
			}
		}
		this.renderJson(list);
	}
	
	/**
	 * 删除智能表单页面
	 */
	public void deleteSmartForm(){
		String absolutePath=this.getAbsolutePath();
		
		for(Long pageId : ids){
			SmPageForm delForm=pageMgmtService.get(pageId);
			
			//执行删除操作
			pageMgmtService.deleteSmartForm(pageId,absolutePath);
			
			String username=this.getLoginUserName();
			String msg="删除了表单，表单编码为“"+delForm.getPageCode()+"”";
			log.info(username+SysTraceLogWriter.MESSAGE_SEPARATOR+msg);
		}
		
	}
	
	@Override
	protected void prepareModel() throws Exception {
		if(id!=null){
			form=pageMgmtService.get(id);
		}else{
			form=new SmPageForm();
		}
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public SmPageForm getModel() {
		return form;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public Page<SmPageForm> getPage() {
		return page;
	}

	public void setPage(Page<SmPageForm> page) {
		this.page = page;
	}

	public String getNodeId() {
		return nodeId;
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}
	
	/**
	 * 设置表单访问路径
	 * @param formPathPrefix
	 */
	private void setFormPath(String formPathPrefix){
		List<SmPageForm> list=page.getResult();
		for(SmPageForm form : list){
			if(form.getTemplateId()==null){
				form.setVisitPath(formPathPrefix+form.getPageCode());
			}else{
				form.setVisitPath("请在流程框架中访问");
			}
		}
	}
	
	/**
	 * 得到当前节点的子节点
	 * @param node
	 * @return
	 */
	private List<SmartPageTreeNode> getChildren(MultiEntityTreeNode node){
		List<SmartPageTreeNode> result=new ArrayList<SmartPageTreeNode>();
		if(node != null){
			// 获取顶级页面目录和未分类页面
			if(MultiEntityTreeNode.isRootNode(node.getId())){
				List<SmPageDirForm> list=pageDirService.getAllTopDir();
				result=PageDirConverter.convertPageDirToTreeNode(list);
				this.addNoDirSmPage(result);
			}else if(node.getEntityName().equals(SmPageDir.class.getSimpleName())){
				Long dirId=node.getEntityId();
				List<SmPageDirForm> list=pageDirService.getChildDir(dirId);
				result=PageDirConverter.convertPageDirToTreeNode(list);
				this.addChildSmPage(result, dirId);
			}
		}
		return result;
	}
	
	/**
	 * 添加没有分类的页面
	 * @param result
	 */
	private void addNoDirSmPage(List<SmartPageTreeNode> result){
		List<SmPageForm> smPageList=pageMgmtService.getNoDirSmPages();
		List<SmartPageTreeNode> noDirTreeNodes=PageConverter.convertPageDirToTreeNode(smPageList);
		result.addAll(noDirTreeNodes);
	}
	
	/**
	 * 添加子页面到树中
	 * @param result
	 * @param parentDirId
	 */
	private void addChildSmPage(List<SmartPageTreeNode> result,Long parentDirId){
		List<SmPageForm> smPageList=pageMgmtService.getSmPageByDirId(parentDirId);
		List<SmartPageTreeNode> noDirTreeNodes=PageConverter.convertPageDirToTreeNode(smPageList);
		result.addAll(noDirTreeNodes);
	}
}
